package code.example.tool;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicLong;

public class FixedThreadPool {

    ExecutorService fixExecutorService;
    public FixedThreadPool(int threadNum){
        ExecutorService executorService = Executors.newFixedThreadPool(threadNum);
        this.fixExecutorService = executorService;
    }
    public FixedThreadPool(int threadNum,final String threadNamePrefix){
        fixExecutorService =  new ThreadPoolExecutor(threadNum, threadNum,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>(), new ThreadFactory() {
            AtomicLong atomicLong = new AtomicLong();
            @Override
            public Thread newThread(Runnable r) {
                long number = atomicLong.incrementAndGet();
                return new Thread(r,threadNamePrefix+"-Thread-"+number);
            }
        });
    }
    public void execute(Runnable runnable){
        fixExecutorService.execute(runnable);
    }
    public void awaitTermination(int time, TimeUnit timeUnit) {
          try {
              fixExecutorService.shutdown();
              fixExecutorService.awaitTermination(time, timeUnit);

          }catch (Exception e){e.printStackTrace();}
    }
}
